package com.szwistar.common.comm;

import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;

/**
 * 用于 ServerBase 的子连接对象基础实现
 * <p>每一个 ServerPeerBase 代表着 ServerBase Accept 的一个子连接。应用程序可以在此基础上实现更多功能。
 */
public class ServerPeerBase implements CommEndpoint {
    protected static final Logger LOG = LoggerFactory.getLogger(ServerPeerBase.class);

    IoSession session;

    public ServerPeerBase() { }

    @Override
    public IoSession getSession() { return session; }

    @Override
    public boolean isConnected() { return session != null && session.isConnected(); }

    @Override
    public void close() { if(session != null) session.close(true); }

    @Override
    public SocketAddress getLocalAddress() { return session.getLocalAddress(); }

    @Override
    public SocketAddress getPeerAddress() { return session.getRemoteAddress(); }

    @Override
    public WriteFuture write(Object message) { return session.write(message); }

    @Override
    public void onCreate(IoSession session, Object context) throws Exception { this.session = session; }

    @Override
    public void onOpened() throws Exception { }

    @Override
    public void onClosed() throws Exception { }

    @Override
    public void onMessageSent(Object message) throws Exception { }

    @Override
    public void onIdle(IdleStatus status) throws Exception { }

    @Override
    public void onExceptionCaught(Throwable cause) throws Exception { }

    @Override
    public void onMessageReceived(Object message) throws Exception { }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "[" + getLocalAddress() + " <- " + getPeerAddress() + "]";
    }
}
